package com.hxh.spring.cloud.emoticon.produce.thread;

import com.hxh.spring.cloud.emoticon.produce.entity.Emoticon;
import com.hxh.spring.cloud.emoticon.produce.service.impl.EmoticonServiceImpl;
import com.hxh.spring.cloud.emoticon.produce.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangxunhui
 * Date: Created in 2019-05-08 21:18
 * Utils: Intellij Idea
 * Description:
 */
@Slf4j
public class EmoticonThread implements Runnable {

    /**
     * Url 目标链接
     */
    private String url;

    /**
     * CSS 样式
     */
    private String clazz;

    private EmoticonServiceImpl emoticonService;

    private RedisUtil redisUtil;

    public EmoticonThread(String url, String clazz, EmoticonServiceImpl emoticonService, RedisUtil redisUtil) {
        this.url = url;
        this.clazz = clazz;
        this.emoticonService = emoticonService;
        this.redisUtil = redisUtil;
    }

    @Override
    public void run() {
        try {
            produce(url,clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void produce(String url, String clazz) throws IOException{
        List<Emoticon> emoticons = new ArrayList<>(68);
        long reqTime=System.currentTimeMillis();
        log.info("url:{}",url);
        Document doc = Jsoup.connect(url).timeout(60000).get();
        log.warn("请求消耗的时间： "+(System.currentTimeMillis()-reqTime)+"ms");

        Elements elements = doc.getElementsByClass(clazz);
        elements.forEach(element -> {
            Emoticon emoticon = new Emoticon();
            emoticon.setTitle(element.attributes().get("alt"));
            emoticon.setUrl(element.attributes().get("data-original").replace("bmiddle","large"));
            emoticons.add(emoticon);
        });

        long startTime=System.currentTimeMillis();
        emoticonService.saveBatch(emoticons);
        log.warn("入库消耗的时间： "+(System.currentTimeMillis()-startTime)+"ms");
        redisUtil.deleteHash("doutula" , url.substring(41));
        log.info("数据爬取成功:{}",url);
    }
}
